package category

import (
	"github.com/lzzyuhyy/framework/mysql"
	"gorm.io/gorm"
)

type Category struct {
	gorm.Model
	PId       int64  `gorm:"type:int(11);not null;default:0;comment('父分类id 一级分类值为0 二级分类为对应父级id')"`
	CateName  string `gorm:"type:varchar(255);not null;comment('分类名称')"`
	CateLevel int8   `gorm:"type:tinyint(1);not null;comment('分类级别 1一级分类 2二级分类')"`
	Order     int64  `gorm:"type:int(11);not null;comment('排序值/优先级')"`
	Img       string `gorm:"type:varchar(255);comment('分类图片')"`
	Status    int8   `gorm:"type:tinyint(1);not null;index;comment('分类状态 0冻结 1正常')"`
}

type CateList struct {
	Category
	SubList []Category
}

// get all cate list with any level
func GetCateListByLevel(level int) (list []Category, err error) {
	err = mysql.CreateMySQLClient(func(db *gorm.DB) error {
		return db.Where("status = 1 and cate_level = ?", level).Find(&list).Error
	})
	return
}

// get cate list with pid--- pid=0:all pid=val:sublist
func GetCateListByPid(pid int) (list []Category, err error) {
	err = mysql.CreateMySQLClient(func(db *gorm.DB) error {
		return db.Where("status = 1 and p_id = ?", pid).Find(&list).Error
	})
	return
}

func GetCateList(pid, level int) (list []Category, err error) {
	err = mysql.CreateMySQLClient(func(db *gorm.DB) error {
		query := db.Where("status = 1")
		if level == 2 && pid == 0 { // 查二级分类数据
			query = db.Where("cate_level = ?", level)
		}
		if level == 1 && pid == 0 { // 查一级分类数据
			query = db.Where("cate_level = ?", level)
		}
		if level == 2 && pid != 0 { // 查询某个一级分类的二级分类数据
			query = db.Where("cate_level = ? and p_id = ?", level, pid)
		}
		if level == 1 && pid != 0 { // 不存在情况
			return err
		}

		return query.Find(&list).Error
	})
	return
}

// search cate by cate name
func GetCateByCateName(name string) (list []Category, err error) {
	err = mysql.CreateMySQLClient(func(db *gorm.DB) error {
		return db.Where("status = 1 and cate_name = ?", name).Find(&list).Error
	})
	return
}

// search cate like cate name
func GetCateLikeCateName(name string) (list []Category, err error) {
	err = mysql.CreateMySQLClient(func(db *gorm.DB) error {
		return db.Where("status = 1 and cate_name like ?", "%"+name+"%").Find(&list).Error
	})
	return
}
